package thulearningcore.util;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

public final class DESCrypto {

	protected final static String key = "ORENOIMOUTOGAKONNANIKAWAIIWAKEGANAI";
	protected final static byte[] iv = { 2, 3, 3, 2, 3, 3, 2, 3 };

	public static String encrypt(String strToEncrypt) {
		if (null == strToEncrypt || strToEncrypt.equals("")) {
			return null;
		}
		try {
			DESKeySpec keySpec = new DESKeySpec(key.getBytes());

			IvParameterSpec zeroIv = new IvParameterSpec(iv);
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey skey = keyFactory.generateSecret(keySpec);
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, skey, zeroIv);
			byte[] encryptedData = cipher.doFinal(strToEncrypt.getBytes());
			return Base64Crypto.encode(encryptedData);
		} catch (Exception e) {
			// e.printStackTrace();
		}
		return null;
	}

	public static String decrypt(String strToDecrypt) {
		if (null == strToDecrypt || strToDecrypt.equals("")) {
			return null;
		}
		try {

			DESKeySpec keySpec = new DESKeySpec(key.getBytes());

			IvParameterSpec zeroIv = new IvParameterSpec(iv);
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey skey = keyFactory.generateSecret(keySpec);

			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, skey, zeroIv);

			byte[] decryptedData = cipher.doFinal(Base64Crypto
					.decode(strToDecrypt));
			return new String(decryptedData);
		} catch (Exception e) {
			// e.printStackTrace();
		}
		return null;
	}
}
